<template>
  <div class="com-container">
    <div class="title" :style="comStyle">
      <span>{{ "▎ " + showTitle }}</span>
      <span class="iconfont icon-arrow-down title-icon" :style="comStyle" @click="showChoice = !showChoice"></span>
      <div class="select-con" v-show="showChoice" :style="marginStyle">
        <div class="select-item" v-for="item in selectTypes" :key="item.key" @click="handleSelect(item.key)">
          {{ item.text }}
        </div>
      </div>
    </div>
    <div class="com-chart" ref="trend_ref"></div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUnmounted, computed } from "vue";
import { getThemeValue } from "@/utils/theme_utils.ts";
import { useThemeChart } from "@/hooks/useThemeChart.ts";

const { proxy } = getCurrentInstance()!;
const trend_ref = ref();
const allData = ref([]);
const echartsInstance = ref(null);
const choiceType = ref("map");
const titleFontSize = ref(0);
const showChoice = ref(false);

// 初始化echartsInstance对象
const initChart = () => {
  echartsInstance.value = proxy!.$echarts.init(trend_ref.value, themeStore.theme);
  // 对图表初始化配置的控制
  const initOption = {
    grid: {
      left: "3%",
      top: "30%",
      right: "4%",
      bottom: "1%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      left: 20,
      top: "15%",
      icon: "circle"
    },
    xAxis: {
      type: "category",
      boundaryGap: false
    },
    backgroundColor: getThemeValue(themeStore.theme).bgColor,
    yAxis: {
      type: "value"
    }
  };
  echartsInstance.value.setOption(initOption);
};

// 获取服务器的数据
const getData = async res => {
  allData.value = res;
  updateChart();
};
const selectTypes = computed(() => {
  if (!allData.value?.type) {
    return [];
  }
  return allData.value.type.filter(item => {
    return item.key !== choiceType.value;
  });
});

const showTitle = computed(() => {
  return allData.value?.[choiceType.value]?.title || "";
});

const marginStyle = computed(() => {
  return {
    marginLeft: titleFontSize.value + "px",
    backgroundColor: getThemeValue(themeStore.theme).bgColor
  };
});

const comStyle = computed(() => {
  return {
    fontSize: titleFontSize.value + "px",
    color: getThemeValue(themeStore.theme).labelColor
  };
});
const handleSelect = (key: string) => {
  choiceType.value = key;
  updateChart();
  showChoice.value = false;
};

// 更新图表
const updateChart = () => {
  // 半透明颜色值
  const colorArr1 = [
    "rgba(73, 146, 255, .5)",
    "rgba(124, 255, 178, .5)",
    "rgba(253, 221, 96, .5)",
    "rgba(255, 110, 118, .5)",
    "rgba(88, 217, 249, .5)"
  ];
  // 全透明颜色值
  const colorArr2 = [
    "rgba(73, 146, 255, 0)",
    "rgba(124, 255, 178, 0)",
    "rgba(253, 221, 96, 0)",
    "rgba(255, 110, 118, 0)",
    "rgba(88, 217, 249, 0)"
  ];
  // 类目轴数据
  const timeArr = allData.value.common.month;
  // y轴数据 series下的数据
  const valueArr = allData.value[choiceType.value].data;

  const seriesArr = valueArr.map((item, index) => {
    return {
      name: item.name,
      type: "line",
      data: item.data,
      smooth: true,
      stack: "map",
      areaStyle: {
        color: new proxy!.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: colorArr1[index]
          },
          {
            offset: 1,
            color: colorArr2[index]
          }
        ])
      }
    };
  });
  // 图例数据
  const legendArr = valueArr.map(item => {
    return item.name;
  });

  const dataOption = {
    xAxis: {
      data: timeArr
    },
    legend: {
      data: legendArr,
      show: true
    },
    series: seriesArr
  };
  echartsInstance.value.setOption(dataOption);
};

const screenAdapter = () => {
  titleFontSize.value = (trend_ref.value.offsetWidth / 100) * 3.6;
  // 和分辨率大小相关的配置项(适配文字标题的大小)
  const adapterOption = {
    legend: {
      itemWidth: titleFontSize.value,
      itemHeight: titleFontSize.value,
      itemGap: titleFontSize.value,
      textStyle: {
        fontSize: titleFontSize.value / 2
      }
    }
  };
  echartsInstance.value.setOption(adapterOption);
  // 手动的调用图表对象的resize 才能产生效果
  echartsInstance.value.resize();
};

const { themeStore } = useThemeChart(echartsInstance, initChart, updateChart, screenAdapter);

onMounted(() => {
  // 注册回调（使用可选链操作符）
  proxy.$socket.registerCallBack("trendData", getData);
  initChart();
  proxy.$socket.send({
    action: "getData",
    socketType: "trendData",
    chartName: "trend",
    value: ""
  });
  window.addEventListener("resize", screenAdapter);
  // 在页面加载完成的时候, 主动进行屏幕的适配
  screenAdapter();
});

onUnmounted(() => {
  // 在组件销毁的时候, 需要将监听器取消掉
  window.removeEventListener("resize", screenAdapter);
  // 注销回调（使用可选链操作符）
  proxy.$socket.unRegisterCallBack("trendData");
});

defineExpose({
  screenAdapter
});
</script>
<style lang="scss" scoped>
.title {
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 9999999999;
  color: white;
  .title-icon {
    margin-left: 10px;
    cursor: pointer;
  }
  .select-con {
    background-color: #222733;
  }
}
</style>
